import { defineComponent, onMounted, provide, ref, watch } from 'vue'
import './index.scss';
import { TabPanesContext, TabsContext, TabsKey } from './types';

export default defineComponent({
  name: 'Tabs',
  props: {
    modelValue: { type: String, default: '' }
  },
  emits: ['update:modelValue'], 

  setup(props, { emit, slots }) {
    console.log(slots.default)
    const panels = ref<TabPanesContext[]>([]);
    const currentTabName = ref(props.modelValue);
    const addPane = (pane: TabPanesContext) => {
      panels.value.push(pane);
    }
    const removePane = (name: string) => {
      if (panels.value.length) {
        const index = panels.value.findIndex(item => item.name === name)
        if (index > -1) panels.value.splice(index , 1)
      }
    }
    provide<TabsContext>(TabsKey, {
      addPane,
      removePane
    });
    const updatePaneVisible = () => {
      if (panels.value.length) {
        panels.value.forEach(item => {
          item.changeShow(item.name === currentTabName.value)
        })
      }
    };
    onMounted(() => {
      if (!currentTabName.value && panels.value.length) {
        currentTabName.value = panels.value[0].name;
        emit('update:modelValue', panels.value[0].name)
      }
      updatePaneVisible();
    });
    watch(() => props.modelValue, newVal => {
      currentTabName.value = newVal;
      updatePaneVisible()
    }, /*{immediate: true}*/);
    function tabClick(name: string) {
      if (name !== currentTabName.value) {
        emit('update:modelValue', name)
      }
    }
    function renderNavs() {
      return panels.value.map(item => {
        const extraCls = item.name === currentTabName.value ? 'active' : '';
        return <div class={ "ant-tab-pane " + extraCls } onClick={ tabClick.bind(null, item.name) }>
          { item.titleSlot ? item.titleSlot(item.name) : item.name }
        </div>
      })
    }
    return () => {
      return (
        <div class="ant-tabs">
          <div class="navs">
            <div class="navs">{ renderNavs.bind(this)() }</div>
          </div>
          { slots.default!()}
        </div>
      )
    }
  }
})

